/**
 * Copyright 厦门中软海晟信息技术有限公司 版权所有 违者必究 2019
 */
package com.opencvjava.lessons2;

import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import static com.opencvjava.support.util.CvUtils.imshow;
import static com.opencvjava.support.util.CvUtils.mat;

/**
 * @author : sunzb(sunzb@hsit.com.cn)
 * @date: 2019/1/15
 */
@Service
public class FaceDemo {
    private final Logger logger = LoggerFactory.getLogger(FaceDemo.class);
    @Value("${project.opencv.root}")
    private String opencvRoot;

    public void test() {
        Mat src = mat("faces","3.jpg");
        if (src.empty()) {
            throw new RuntimeException("图片读取失败");
        }
        imshow("源图", src);
        String dataPath = opencvRoot + "/etc/haarcascades/haarcascade_frontalface_alt_tree.xml";
        CascadeClassifier detector = new CascadeClassifier();
        if (detector.load(dataPath)) {
            MatOfRect faces = new MatOfRect();
            detector.detectMultiScale(src, faces, 1.1, 1, 0,
                    new Size(5, 5), new Size(100, 100));
            Rect[] rects = faces.toArray();
            Mat result = src.clone();
            for (Rect rect : rects) {
                Imgproc.rectangle(result, rect.tl(), rect.br(), new Scalar(0, 0, 255), 2);
            }
            imshow("结果", result);
        }
    }
}
